const fs = require("fs");
const http = require("http");
const path = require("path");
// express:res.send
function reWriteRes(res) {
    res.send = function (txt) {
        res.writeHead(200, { 'Content-Type': "text/html;charset=UTF8" });
        res.end(txt)
    }
}
// 获取mine
function getMine(extname){
    extname=extname.slice(extname.indexOf('.')+1)
    try{
        let data=fs.readFileSync("./data/mine.json");
        if(data){
            return JSON.parse(data.toString())[extname]
        }
    }catch(err){
        res.send('当前没有匹配mine')
    }
}
// 静态服务目录
function initStaticWeb(req, res, staticPath) {
    let pathname = req.url;
    // 默认/为index.html
    pathname=pathname=='/'?'/index.html':pathname
    console.log(pathname)
    // 获取后缀
    let extname = path.extname(pathname);
    if (extname) {
        try {
            let data = fs.readFileSync(staticPath + pathname);
            res.writeHead(200, { 'Content-Type': getMine(extname)+";charset=UTF8" });
            res.end(data)
        } catch (err) {
            res.send('当前静态资源不存在')
        }
    }

}
const server = () => {
    let G = {
        _GET: {},
        _POST: {},
        staticPath: 'static'
    }
    // 执行app方法
    let app = function (req, res) {
        // 重写res.end
        reWriteRes(res)
        // 配置静态服务目录
        initStaticWeb(req, res, G['staticPath'])


        let pathname = req.url;
        // 获取后缀
        let extname = path.extname(pathname);
        // 获取请求类型
        let method = req.method;
        // 如果不含有后缀则进入路由
        if (!extname) {
            if (G['_' + method][pathname]) {
                if (method == 'GET') {
                    G['_GET'][pathname](req, res)
                } else {
                    // 获取post参数
                    let postData = "";
                    req.on("data", (data) => {
                        postData += data
                    })
                    req.on("end", () => {
                        req.body = postData;
                        G['_POST'][pathname](req, res)
                    })
                }
            } else {
                res.send("页面不存在")
            }
        }

    }
    // 配置get路由
    app.get = function (str, cb) {
        // 注册方法
        G._GET[str] = cb
    }
    // 配置post路由
    app.post = function (str, cb) {
        // 注册方法
        G._POST[str] = cb
    }
    // 配置静态服务器目录
    app.static = function (staticPath) {
        G.staticPath = staticPath
    }
    return app
}


module.exports = server()